﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using HelpCentral.Shared.Security;
using HelpCentral.Shared.Interfaces;
using HelpCentral.Configuration;
using HelpCentral.Core.Objects;
using HelpCentral.Data.Repository;
using HelpCentral.Shared.Enums;

namespace HelpCentral.Core.Services
{
    public class UserService
    {
        public UserService()
        {
            CoreContainer.Register<IUser, UserInfo>();
            CoreContainer.Register<IUserRepository, UserRepository>();
        }

        public IUser CreateSystemUser()
        {
            var systemUser = GetSystemUser();

            if (systemUser != null)
            {
                return systemUser;
            }

            var ur = CoreContainer.ResolveNew<IUserRepository>();
            var u = CoreContainer.ResolveNew<IUser>();

            u.Username = "system";
            u.PasswordHash = PasswordUtility.HashPassword("system");
            u.PasswordExpirationDate = DateTime.UtcNow;
            u.ActivateDate = DateTime.UtcNow;

            return SaveUser(u);
        }

        public IUser GetSystemUser()
        {
            var ur = CoreContainer.ResolveNew<IUserRepository>();
            return ur.FetchUserByUsername(null, "system");
        }

        public IUser SaveUser(IUser user)
        {
            user.Validate();

            var ur = CoreContainer.ResolveNew<IUserRepository>();
            bool isNew = ur.FetchUserById(user.UserId) == null;

            user = ur.CommitUser(user);

            if (isNew)
            {
                new AuditService().SaveAuditEvent(AuditEventType.CreateUserEvent, user.Client, "Added new user with username '" + user.Username + "'", user.UserId);
            }
            else
            {
                new AuditService().SaveAuditEvent(AuditEventType.UpdateUserEvent, user.Client, "Updated user", user.UserId);
            }

            return user;
        }
    }
}
